import * as step from '@flow-step/step-toolkit'
import axios, {AxiosError} from 'axios';
const https = require('https');

const agent = new https.Agent({
    rejectUnauthorized: false // 设置为 false 来忽略证书验证
});
import process from 'process'
import {polyglot} from './i18n'
export function Run() {
    step.info('trigger codeup scan task')
    const codeupSource   = process.env['codeupSource'] as string
    const flowPipelineSources   = process.env['SOURCES'] as string
    var source = JSON.parse(codeupSource)
    if(flowPipelineSources){
        JSON.parse(flowPipelineSources).forEach(function (flowPipelineSource: any) {
            if(flowPipelineSource.sign === source.sign){
                source = flowPipelineSource;
            }
        })
    }
    const serverURL = process.env[`FLOW_OPENAPI_URL`] as string

    const url = `${serverURL}/openapi/codeup/api/scanTask/execute`;
    let referName = source.data.branch;
    var callbackUrl = step.callbackUrl()
    step.info("callbackUrl:"+callbackUrl)
    const params = {
        projectId: source.data.projectId,
        connectionId: source.data.connection,
        callbackUrl: callbackUrl,
        referName: referName,
        flowJobToken:  process.env[`FLOW_JOB_TOKEN`]
    };

    step.info(polyglot.t("trigger_code_detection"))
    axios.request({
        method: 'POST',
        url: url,
        params: params,
        httpsAgent: agent
    }).then(function (response) {
        step.info(`${polyglot.t("trigger_result")}：`+JSON.stringify(response.data))
        if (typeof response.data === 'object' && response.data !== null && response.data && 'successful' in response.data && response.data.successful == false) {
            step.error(`${polyglot.t("trigger_failed")}: `+response.data.errorMsg)
            process.exit(-1)
        }
    }).catch((error: AxiosError) => {
        throw new Error(`error: ${error.code} ${JSON.stringify(error.response?.data)}`);
    });
    // 等待执行结果
    step.interaction.appendMessage(polyglot.t("waiting_for_scan_results"))
    const actions = [];
    actions.push({
        type: 'HIDDEN',
        action: 'WAIT',
        name: polyglot.t("scan_results"),
        order: 1,
        hidden: true
    })
    step.interaction.appendActions(actions)

}
async function runStep(): Promise<void> {
    var COMMAND = process.env['COMMAND']

    switch (COMMAND) {
        case 'RUN':
            Run();
            break;
        default:
            step.info('Invalid action. Please provide Run .')

    }
}

 runStep()
    .then(function () {

    })
    .catch(function (err: Error) {
        step.error(err.message)
        process.exit(-1)
    })
